package com.javacv.plus.examples;

import com.javacv.plus.starter.JavaCVPlusStarter;
import com.javacv.plus.extensions.image.ImageProcessor;
import com.javacv.plus.extensions.image.ProcessorResult;
import com.javacv.plus.extensions.image.config.ImageConfig;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Starter功能测试
 * 实际测试JavaCV Plus Starter的各种功能
 */
@Slf4j
public class StarterFunctionalTest {
    
    private static final String TEST_IMAGE_PATH = "/Users/xiongguochao/00-cursor/javacv-plus/image/test.jpg";
    private static final String OUTPUT_DIR = "/Users/xiongguochao/00-cursor/javacv-plus/output/";
    
    public static void main(String[] args) {
        log.info("=== JavaCV Plus Starter 功能测试 ===");
        
        // 确保输出目录存在
        ensureOutputDirectory();
        
        // 测试1: Starter初始化和系统信息
        testStarterInitialization();
        
        // 测试2: 使用Starter创建图像处理器
        testImageProcessorCreation();
        
        // 测试3: 不同配置的图像处理
        testDifferentConfigurations();
        
        // 测试4: 批量处理测试
        testBatchProcessing();
        
        log.info("\n🎉 所有Starter功能测试完成！");
    }
    
    /**
     * 确保输出目录存在
     */
    private static void ensureOutputDirectory() {
        File outputDir = new File(OUTPUT_DIR);
        if (!outputDir.exists()) {
            boolean created = outputDir.mkdirs();
            if (created) {
                log.info("📁 创建输出目录: {}", OUTPUT_DIR);
            } else {
                log.warn("⚠️ 无法创建输出目录: {}", OUTPUT_DIR);
            }
        }
    }
    
    /**
     * 测试Starter初始化和系统信息
     */
    private static void testStarterInitialization() {
        log.info("\n🔧 测试 1: Starter初始化和系统信息");
        log.info("================================================");
        
        try {
            // 显式初始化
            JavaCVPlusStarter.initialize();
            
            // 打印系统信息
            JavaCVPlusStarter.printSystemInfo();
            
            log.info("✅ 初始化状态: {}", JavaCVPlusStarter.isInitialized());
            log.info("✅ 当前平台: {}", JavaCVPlusStarter.getCurrentPlatform().getPlatformString());
            log.info("✅ CPU核心数: {}", JavaCVPlusStarter.getSystemInfo().getAvailableProcessors());
            
        } catch (Exception e) {
            log.error("❌ Starter初始化测试失败", e);
        }
    }
    
    /**
     * 测试图像处理器创建
     */
    private static void testImageProcessorCreation() {
        log.info("\n🖼️ 测试 2: 图像处理器创建");
        log.info("================================================");
        
        try {
            // 检查测试图片是否存在
            File testImage = new File(TEST_IMAGE_PATH);
            if (!testImage.exists()) {
                log.warn("⚠️ 测试图片不存在: {}", TEST_IMAGE_PATH);
                log.info("ℹ️ 跳过实际图像处理，仅测试API创建");
                
                // 仅测试API，不实际处理
                ImageProcessor processor = JavaCVPlusStarter.createImageProcessor("dummy.jpg");
                log.info("✅ 图像处理器创建成功 (API测试)");
                return;
            }
            
            log.info("📥 测试图片: {}", TEST_IMAGE_PATH);
            
            // 使用默认配置创建处理器
            ImageProcessor processor = JavaCVPlusStarter.createImageProcessor(TEST_IMAGE_PATH);
            log.info("✅ 使用默认配置创建处理器成功");
            
            // 基本图像处理
            String outputPath = OUTPUT_DIR + "starter_basic_output.jpg";
            ProcessorResult result = processor
                    .resize(400, 300)
                    .blur(3)
                    .save(outputPath);
            
            if (result != null && result.isSuccess()) {
                log.info("✅ 基本图像处理成功: {}", outputPath);
            } else {
                log.error("❌ 基本图像处理失败");
            }
            
        } catch (Exception e) {
            log.error("❌ 图像处理器创建测试失败", e);
        }
    }
    
    /**
     * 测试不同配置的图像处理
     */
    private static void testDifferentConfigurations() {
        log.info("\n⚙️ 测试 3: 不同配置的图像处理");
        log.info("================================================");
        
        try {
            File testImage = new File(TEST_IMAGE_PATH);
            if (!testImage.exists()) {
                log.warn("⚠️ 测试图片不存在，跳过配置测试");
                return;
            }
            
            // 测试性能优化配置
            log.info("🚀 测试性能优化配置...");
            ImageConfig performanceConfig = JavaCVPlusStarter.createPerformanceConfig();
            log.info("   质量: {}%, 格式: {}", 
                    performanceConfig.getQuality(), 
                    performanceConfig.getOutputFormat());
            
            ImageProcessor performanceProcessor = JavaCVPlusStarter.createImageProcessor(
                    TEST_IMAGE_PATH, performanceConfig);
            String performanceOutput = OUTPUT_DIR + "starter_performance_output.jpg";
            performanceProcessor
                    .scale(0.8)
                    .gaussianBlur(0.3)
                    .save(performanceOutput);
            log.info("✅ 性能优化处理完成: {}", performanceOutput);
            
            // 测试高质量配置
            log.info("🎨 测试高质量配置...");
            ImageConfig highQualityConfig = JavaCVPlusStarter.createHighQualityConfig();
            log.info("   质量: {}%, 格式: {}", 
                    highQualityConfig.getQuality(), 
                    highQualityConfig.getOutputFormat());
            
            ImageProcessor highQualityProcessor = JavaCVPlusStarter.createImageProcessor(
                    TEST_IMAGE_PATH, highQualityConfig);
            String highQualityOutput = OUTPUT_DIR + "starter_highquality_output.png";
            highQualityProcessor
                    .resize(600, 400)
                    .brightness(1.1)
                    .contrast(1.2)
                    .save(highQualityOutput);
            log.info("✅ 高质量处理完成: {}", highQualityOutput);
            
            // 测试快速处理方法
            log.info("⚡ 测试快速处理方法...");
            String quickOutput = OUTPUT_DIR + "starter_quick_output.jpg";
            boolean quickResult = JavaCVPlusStarter.quickProcess(TEST_IMAGE_PATH, quickOutput);
            log.info("✅ 快速处理结果: {}", quickResult ? "成功" : "失败");
            
        } catch (Exception e) {
            log.error("❌ 配置测试失败", e);
        }
    }
    
    /**
     * 测试批量处理
     */
    private static void testBatchProcessing() {
        log.info("\n📦 测试 4: 批量处理");
        log.info("================================================");
        
        try {
            File testImage = new File(TEST_IMAGE_PATH);
            if (!testImage.exists()) {
                log.warn("⚠️ 测试图片不存在，跳过批量处理测试");
                return;
            }
            
            // 模拟批量处理多张图片
            List<String> inputPaths = new ArrayList<>();
            inputPaths.add(TEST_IMAGE_PATH); // 实际上只有一张图片，但模拟多张的处理逻辑
            
            long startTime = System.currentTimeMillis();
            
            for (int i = 0; i < inputPaths.size(); i++) {
                String inputPath = inputPaths.get(i);
                String outputPath = OUTPUT_DIR + "batch_" + (i + 1) + ".jpg";
                
                log.info("🔄 处理 {}/{}: {} -> {}", 
                        i + 1, inputPaths.size(), 
                        new File(inputPath).getName(), 
                        new File(outputPath).getName());
                
                ImageProcessor processor = JavaCVPlusStarter.createImageProcessor(inputPath);
                ProcessorResult result = processor
                        .resize(300, 200)
                        .grayscale()
                        .addBorder(5, 128, 128, 128)
                        .save(outputPath);
                
                if (result != null && result.isSuccess()) {
                    log.info("   ✅ 处理成功");
                } else {
                    log.error("   ❌ 处理失败");
                }
            }
            
            long duration = System.currentTimeMillis() - startTime;
            log.info("📊 批量处理统计:");
            log.info("   总耗时: {}ms", duration);
            log.info("   处理图片: {}张", inputPaths.size());
            log.info("   平均耗时: {}ms/张", duration / inputPaths.size());
            
        } catch (Exception e) {
            log.error("❌ 批量处理测试失败", e);
        }
    }
} 